<?php
header('Content-Type: text/plain');
require_once dirname(__FILE__) . '/../../common.inc.php';

$myPdo = DbUtils::createPdoInst();

$action = MiscUtils::getParam('action', NULL);
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'uninstall':
      uninstall($myPdo);
      break;
    case 'delete':
      delete($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo ERROR_SIGN . $e->getMessage();
}

function uninstall($myPdo) {
  require_once dirname(__FILE__) . '/Plugin.class.php';
  $obj = new Plugin();
  
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  
  $instance_id = $q->i;
  
  rrmdir('uploads/' . $instance_id);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'instance_id = ?';
  $cond_vals->v = array($instance_id);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . $obj->folder . '_image', $cond_vals);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . $obj->folder . '_config', $cond_vals);
  $cond_vals->c = 'id = ?';
  $cond_vals->v = array($instance_id);
  DbUtils::deleteByCond($myPdo, 'pz_plugin_instance', $cond_vals);
  echo json_encode(array());
}

function delete($myPdo) {
  require_once dirname(__FILE__) . '/Plugin.class.php';
  $obj = new Plugin();
  
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  if (file_exists($q->link)) {
    unlink($q->link);
  }
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'id = ?';
  $cond_vals->v = array($q->id);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . $obj->folder . '_image', $cond_vals);
  echo json_encode(array());
}

function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir . "/".$object) == "dir") {
           rrmdir($dir."/".$object); 
        } else {
          unlink($dir."/".$object);
        }
      }
    }
    reset($objects);
    rmdir($dir);
  }
} 
?>